﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace AndreasJohansson.AutoMailic
{
  class ConfigurationFile
  {
    /// <summary>
    /// Constructor
    /// </summary>
    public ConfigurationFile()
    {
    }

    /// <summary>
    /// Loads configuration and gets section(s) to process
    /// </summary>
    /// <param name="configurationFile">Configuration file</param>
    /// <param name="sectionName">Name of section to process, if empty process all sections.</param>
    public void Load(string configurationFile, string sectionName)
    {
      LoadConfigurationFile(configurationFile);
      GetConfigurationSections(sectionName);
    }

    /// <summary>
    /// Sections to process
    /// </summary>
    public List<ConfigurationSection> Sections
    {
      get
      {
        return _sections;
      }
    }

    /// <summary>
    /// Load the XML configuration file
    /// </summary>
    /// <param name="configurationFile">Configuration file</param>
    private void LoadConfigurationFile(string configurationFile)
    {
      _xmlDocument = new XmlDocument();
      try
      {
        _xmlDocument.Load(configurationFile);
      }
      catch (SystemException ex)
      {
        throw new AutoMailicException("An system exception occured while trying to load the XML configuration file", ex);
      }
    }

    /// <summary>
    /// Get the configuration sections to process
    /// </summary>
    /// <param name="sectionName">Name of section, if null or empty it will get all sections in file</param>
    private void GetConfigurationSections(string sectionName)
    {
      // Get sections
      string xpath = "/automailic/configSection";
      if (false == String.IsNullOrEmpty(sectionName))
      {
        xpath += "[@name = \"" + sectionName + "\"]";
      }
      XmlNodeList sectionNodes = _xmlDocument.SelectNodes(xpath);

      // Generate the section nodes
      foreach (XmlNode sectionNode in sectionNodes)
      {
        ConfigurationSection configSection = new ConfigurationSection(sectionNode);
      }
    }

    /// <summary>List of configuration sections to process</summary>
    private List<ConfigurationSection> _sections = new List<ConfigurationSection>();
    /// <summary>The xml document for the configuration file</summary>
    private XmlDocument _xmlDocument = null;
  }
}
